﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using Core.Base;
using Global.Mgr;
using NetData.Base;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using UnityEditor;
using UnityEngine;
using UnityEngine.Networking;

namespace Core.Mgrs
{
    public class WebMgr : BaseMgr
    {
        /// <summary>
        /// 请求Texture
        /// </summary>
        /// <param name="url"></param>
        /// <param name="cb"></param>
        public void ReqTexture(string url, Action<Texture> cb = null)
        {
            if (string.IsNullOrEmpty(url))
            {
                return;
            }

            UnityWebRequest webRequest = new UnityWebRequest(url);
            DownloadHandlerTexture downloadTexture = new DownloadHandlerTexture(true);
            webRequest.downloadHandler = downloadTexture;
            KKGL.MainBehaviour.StartCoroutine(SendWebRequest(webRequest, () =>
            {
                Texture texture = DownloadHandlerTexture.GetContent(webRequest);
                cb?.Invoke(texture);
            }));
        }

        /// <summary>
        /// 请求AudioClip
        /// </summary>
        /// <param name="url"></param>
        /// <param name="cb"></param>
        /// <param name="audioType"></param>
        public void ReqAudioClip(string url, Action<AudioClip> cb = null, AudioType audioType = AudioType.MPEG)
        {
            UnityWebRequest www = UnityWebRequestMultimedia.GetAudioClip(url, audioType);
            KKGL.MainBehaviour.StartCoroutine(SendWebRequest(www, () =>
            {
                AudioClip clip = DownloadHandlerAudioClip.GetContent(www);
                cb?.Invoke(clip);
            }));
        }

        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="url">远端地址</param>
        /// <param name="downloadFilePathAndName">文件下载后的保存路径（包含文件名）</param>
        public void DownloadFile(string url, string downloadFilePathAndName, Action<float> downloadProgress,
            Action finishCb)
        {
            UnityWebRequest uwr = new UnityWebRequest(url, UnityWebRequest.kHttpVerbGET);
            uwr.downloadHandler = new DownloadHandlerFile(downloadFilePathAndName);
            uwr.SetRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            uwr.useHttpContinue = false;
            uwr.timeout = 2;
            uwr.SendWebRequest();
            while (!uwr.isDone)
            {
                downloadProgress?.Invoke(uwr.downloadProgress);
            }

            if (uwr.isDone && uwr.error == null)
            {
                finishCb?.Invoke();
            }


            // KKGL.MainBehaviour.StartCoroutine(SendWebRequest(uwr, delegate { uwr.Dispose(); }));
        }

        /// <summary>
        /// 创建一个webRequest对象
        /// </summary>
        /// <param name="url">目标URL</param>
        /// <param name="jsonData">上传到server的数据</param>
        /// <param name="contentType">上传数据内容协议类型</param>
        /// <param name="verb">要启动的Web请求的动作</param>
        /// <returns></returns>
        private UnityWebRequest CreateWebRequest(string url, string jsonData = "", string contentType = null,
            string verb = UnityWebRequest.kHttpVerbPOST)
        {
            UnityWebRequest webRequest = new UnityWebRequest();
            webRequest.url = url;
            webRequest.method = verb;
            if (!string.IsNullOrEmpty(jsonData))
            {
                webRequest.uploadHandler = new UploadHandlerRaw(Encoding.UTF8.GetBytes(jsonData));
            }

            if (!string.IsNullOrEmpty(contentType))
            {
                webRequest.SetRequestHeader("Content-Type", contentType);
            }


            webRequest.timeout = 10;
            webRequest.useHttpContinue = false;
            webRequest.downloadHandler = new DownloadHandlerBuffer();
            return webRequest;
        }


        private IEnumerator SendWebRequest(UnityWebRequest webRequest, Action callback)
        {
            webRequest.timeout = 5;
            yield return webRequest.SendWebRequest();
            if (webRequest.result == UnityWebRequest.Result.ConnectionError)
            {
                Debug.Log(webRequest.result);
            }
            else
            {
                callback?.Invoke();
            }

            webRequest.Dispose();
        }
    }
}